import { LoggerService } from '@nestjs/common';
import { createLogger, format, Logger, transports } from 'winston';
import * as chalk from 'chalk';
import * as dayjs from 'dayjs';

// 封装 winston 日志的动态模块
export class MyLogger implements LoggerService {
    private logger: Logger;
    constructor() {
        this.logger = createLogger({
            level: 'debug',
            // format: format.combine(format.colorize(), format.simple()), // 使用自定义的时间戳和颜色
            transports: [
                // 打印日志
                new transports.Console({ // 配置自定义的时间戳和颜色
                    format: format.combine(
                        format.colorize(),
                        format.printf(({ context, level, message, time }) => {
                            const appStr = chalk.green(`[NEST]`);
                            const contextStr = chalk.yellow(`[${context}]`);
                            return `${appStr} ${time} ${level} ${contextStr} ${message}`;
                        }),
                    ),
                }),
                // 输出文件
                // new transports.File({
                //     format: format.combine(
                //         format.timestamp(),
                //         format.json()
                //     ),
                //     filename: 'test.log',
                //     dirname: 'log'
                // })
            ],
        });
    }

    log(message: string, context: string) {
        const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
        this.logger.log('info', message, { context, time });
    }

    error(message: string, context: string) {
        const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
        this.logger.log('info', message, { context, time });
    }

    warn(message: string, context: string) {
        const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
        this.logger.log('info', message, { context, time });
    }
}
